<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/10/12
 * Time: 15:01
 */

namespace app\index\controller;
use app\common\controller\Base;
use think\facade\Request;
use app\common\model\User as UserModel;
use think\facade\Session;

class User extends Base
{
    public function register(){
        //检测是否允许注册
        $this->is_reg();

        $this->logined();
        $this->assign('title','用户注册');
        return $this->view->fetch();
    }

    public function insert(){
        if( ! Request::isAjax()){
            return $this->error('请求类型错误', 'register');
        }
        $data = Request::post();
        $rule = 'app\common\validate\User';
        $res = $this->validate($data, $rule);

        if (true !== $res){
            return ['status'=>0, 'msg'=>$res];
        }
        $data = Request::except('password_confirm', 'post');
        if ($user = UserModel::create($data)){
            $res = UserModel::get($user->id);
            Session::set('user_id', $res->id);
            Session::set('user_name', $res->name);
            return ['status'=>1, 'msg'=>'恭喜，注册成功'];
        }
        return ['status'=>0, 'msg'=>'注册失败，请检查'];
    }

    public function login(){
        $this->logined();
        $this->assign('title', '用户登录');
        return $this->view->fetch();
    }

    public function loginCheck(){
        if ( ! Request::isAjax()){
            return $this->error('请求类型错误','login');
        }
        $data = Request::post();
        $rule = [
            'email|邮箱'      => 'require|email',
            'password|密码'   => 'require|alphaNum'
        ];
        $res = $this->validate($data, $rule);
        if (true !== $res){
            return ['status'=>0, 'msg'=>$res];
        }
        $result = UserModel::get(function ($query) use($data) {
            $query->field('id,name,email,password')->where('email', $data['email']);
        });
        if ($result->password != sha1($data['password'])){
            return ['status'=>0, 'msg'=>'邮箱或者密码不正确'];
        }
        Session::set('user_id', $result->id);
        Session::set('user_name', $result->name);
        return ['status'=>1, 'msg'=>'恭喜，登录成功'];
    }

    public function logout(){
//        Session::delete('user_id');
//        Session::delete('user_name');
        Session::clear();
        return $this->success('退出成功', 'index/index');
    }
}